<template>
    <div class="container">
        <HeaderBar>
            <template slot="titleBar">
                <div class="container-title">
                    <img v-if="isWx" class="back" :src="imgs.back" alt="" @click="back" />
                    <span>卡详情</span>
                </div>
            </template>
        </HeaderBar>

        <div class="card-detail">
            <img :src="imgs.cardBg" alt="卡背景" />
            <div class="card-detail__title">余额(元)</div>
            <div class="card-detail__total">{{ (cardDetail.balance / 100).toFixed(2) }}</div>
            <div class="card-detail__recharge" @click="showRechargeModal">充值</div>
            <div class="card-detail__no">{{ cardDetail.card_no }}</div>
        </div>

        <template>
            <Tabs style="flex: auto; overflow: auto" v-model="tabIndex" :list="list">
                <template v-slot:[getSlotName(index)] v-for="(item, index) in list">
                    <div class="list" :class="[`list_${index}`]" :key="index">
                        <template v-if="cardArr[index].length">
                            <!-- 消费记录 -->
                            <template v-if="tabIndex === 0">
                                <div class="card-item card-consume" v-for="(item2, i) in cardArr[index]" :key="i">
                                    <div class="card-item__top">
                                        <div class="card-item__title">
                                            <img :src="imgs.cardRecharge" alt="" />
                                            充电扣费
                                        </div>
                                        <div class="card-item__value">-{{ (item2.payAmount / 100).toFixed(2) }}</div>
                                    </div>
                                    <div v-if="item2.refundAmount" class="card-item__refund">退款金额：{{ (item2.refundAmount / 100).toFixed(2) }}元</div>
                                    <div class="card-item__bottom">
                                        <div class="card-item__text">{{ item2.orderNo }}</div>
                                        <div class="card-item__text">{{ item2.payTime }}</div>
                                    </div>
                                </div>
                            </template>
                            <!-- 充值记录 -->
                            <template v-if="tabIndex === 1">
                                <div class="card-item card-recharge" v-for="(item2, i) in cardArr[index]" :key="i">
                                    <div class="card-item__top">
                                        <div class="card-item__title">
                                            <img :src="imgs.cardConsume" alt="" />
                                            {{ rechargeMap[item2.optType] }}
                                        </div>
                                        <div class="card-item__value">+{{ (item2.amount / 100).toFixed(2) }}</div>
                                    </div>
                                    <div class="card-item__bottom">
                                        <div class="card-item__text"></div>
                                        <div class="card-item__text">{{ item2.rechargeTime }}</div>
                                    </div>
                                </div>
                            </template>

                            <div v-if="hasMoreArr[index]" class="load-more" @click="getCardList">加载更多</div>
                            <div v-else class="no-more">已加载全部</div>
                        </template>
                        <div v-else class="empty">暂无数据</div>
                    </div>
                </template>
            </Tabs>
        </template>

        <!-- 实体卡充值 -->
        <ant-modal :visible="rechargeVisible" bodyStyle="padding: 0; width: auto; border-radius: none; background-color: transparent">
            <template #content>
                <div class="bind-modal" style="height: 420rpx">
                    <!-- <div class="modal-title">充值卡号</div>
                    <div class="modal-input">
                        <input v-model="cardDetail.card_no" disabled type="text" placeholder="请输入卡号" />
                    </div> -->
                    <div class="modal-title">充值金额</div>
                    <div class="modal-input">
                        <input v-model="recharge_amount" type="text" placeholder="请输入充值金额(元)" />
                    </div>
                    <div class="modal-footer">
                        <div class="modal-btn" @click="rechargeVisible = false">取消</div>
                        <div class="modal-btn confirm" @click="recharge()">确定</div>
                    </div>
                </div>
            </template>
        </ant-modal>
    </div>
</template>
<script>
import { getCardConsumeListAPI, getCardRechargeListAPI, getCardsListAPI, rechargeAPI } from "../src/api/api";
import HeaderBar from "../src/components/HeaderBar.vue";
import Tabs from "../src/components/Tabs.vue";
import StatusTag from "../src/components/StatusTag.vue";
import LoginButton from "../src/components/LoginButton.vue";
import { formatChargingTime } from "../src/libs/utils";

const app = getApp();
export default {
    components: {
        HeaderBar,
        Tabs,
        StatusTag,
        LoginButton,
    },
    data() {
        return {
            isWx: app.globalData.isWx,
            imgs: app.globalData.imgs,
            tabIndex: 0,
            show: false,
            list: ["消费记录", "充值记录"],
            loading: false,

            // 页码
            pageArr: [1, 1],

            // 记录数据
            cardArr: [[], []],

            // 更多数据
            hasMoreArr: [true, true],

            rechargeMap: {
                RECHARGE: "小程序充值",
                MERCHANT_RECHARGE: "商家代充",
            },

            userInfo: {},

            cardDetail: {},

            rechargeVisible: false,
            recharge_amount: 0,
            inRecharging: false
        };
    },
    onShareAppMessage() {},
    onLoad(options) {
        this.userInfo = uni.getStorageSync("userInfo") || {};
        this.cardNo = options.cardNo;
    },
    onShow() {
        console.log("卡详情页 onShow");
        this.userInfo = uni.getStorageSync("userInfo") || {};
        // 重置数据
        this.pageArr = [1, 1];
        this.cardArr = [[], []];
        this.hasMoreArr = [true, true];

        if (this.userInfo.phone) {
            // this.getCardList();
            // this.getCardDetail();
        }
    },
    watch: {
        tabIndex(val) {
            this.pageArr[val] = 1;
            this.cardArr[val] = [];
            this.hasMoreArr[val] = true;
            this.getCardList();
        },
        "userInfo.phone"(val) {
            // 重置数据
            this.pageArr = [1, 1];
            this.cardArr = [[], []];
            this.hasMoreArr = [true, true];

            // 登录时加载数据
            if (val) {
                this.getCardList();
                this.getCardDetail();
            }
        },
    },
    methods: {
        formatChargingTime,
        back() {
            uni.navigateBack();
        },
        getSlotName(i) {
            return "tab" + i;
        },
        // 查询卡详情
        getCardDetail() {
            getCardsListAPI().then((res) => {
                if (this.cardNo === res.virtual_card.card_no) {
                    this.cardDetail = res.virtual_card;
                } else {
                    let list = res.physical_card_list || [];
                    list.forEach((item) => {
                        if (item.card_no === this.cardNo) {
                            this.cardDetail = item;
                        }
                    });
                }
            });
        },
        // 请求充值消费列表
        getCardList() {
            if (this.loading) return false;
            this.loading = true;
            let curIndex = this.tabIndex;
            let api = this.tabIndex === 0 ? getCardConsumeListAPI : getCardRechargeListAPI;
            api({
                cardNo: this.cardNo,
                page: this.pageArr[curIndex],
            })
                .then((res) => {
                    this.cardArr[curIndex] = this.cardArr[curIndex].concat(res.list);
                    this.hasMoreArr[curIndex] = res.list.length === 10;
                    this.pageArr[curIndex]++;
                    this.loading = false;
                })
                .catch((err) => {
                    this.loading = false;
                });
        },
        // 打开充值弹窗
        showRechargeModal() {
            this.recharge_amount = "";
            this.rechargeVisible = true;
        },
        // 充值
        recharge() {
            if(this.inRecharging) return false;
            this.inRecharging = true;
            rechargeAPI({
                amount: this.recharge_amount * 100,
                cardNo: this.cardDetail.card_no,
                payType: this.isWx ? "WECHAT" : "ALIPAY",
            }).then((res) => {
                if (this.isWx) {
                    let chargeData = JSON.parse(res.charge_url);
                    console.log(chargeData);
                    uni.requestPayment({
                        timeStamp: chargeData.timeStamp,
                        nonceStr: chargeData.nonceStr,
                        package: chargeData.package,
                        signType: chargeData.signType,
                        paySign: chargeData.sign,
                        success: () => {
                            uni.showToast({
                                title: "充值成功",
                                icon: "none",
                            });
                            this.rechargeVisible = false;

                            // 重置数据
                            this.pageArr = [1, 1];
                            this.cardArr = [[], []];
                            this.hasMoreArr = [true, true];
                            this.getCardList();
                            this.getCardDetail();
                        },
                        fail: (err) => {
                            console.log("充值成功", err);
                        },
                        complete: () => {
                            this.inRecharging = false;
                            uni.hideLoading();
                        },
                    });
                } else {
                    uni.requestPayment({
                        provider: "alipay",
                        tradeNO: JSON.parse(decodeURIComponent(res.charge_url)).tradeNo,
                        success: (res) => {
                            if (res.resultCode === "9000") {
                                uni.showToast({
                                    title: "充值成功",
                                    icon: "none",
                                });
                                this.rechargeVisible = false;
                                this.getList();
                            } else {
                                uni.showToast({
                                    title: "充值失败",
                                    icon: "none",
                                });
                            }
                        },
                        fail: (err) => {
                            console.log("充值失败", err);
                        },
                        complete: () => {
                            this.inRecharging = false;
                            uni.hideLoading();
                        },
                    });
                }
            });
        },
    },
};
</script>
<style scoped lang="less">
.container {
    height: 100vh;
    box-sizing: border-box;
    overflow: hidden;
    background-color: #f6f6f6;
    display: flex;
    flex-direction: column;

    .container-title {
        display: flex;
        align-items: center;
        font-size: 38rpx;
        line-height: 1;
        font-weight: bold;
        color: #333;

        .back {
            width: 32rpx;
            height: 32rpx;
            margin-left: 28rpx;
            margin-right: 28rpx;
            display: block;
        }
    }

    .card-detail {
        flex: none;
        position: relative;
        width: 694rpx;
        height: 250rpx;
        background: linear-gradient(222.93deg, rgba(139, 218, 176, 1) 0%, rgba(8, 191, 168, 1) 100%);
        box-shadow: 0px 16rpx 24rpx rgba(8, 191, 168, 0.16);
        border-radius: 24rpx;
        margin-bottom: 30rpx;
        margin: 30rpx auto 30rpx;

        img {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
        }

        .card-detail__title {
            font-size: 26rpx;
            color: #fff;
            opacity: 0.8;
            position: absolute;
            top: 28rpx;
            left: 28rpx;
        }

        .card-detail__total {
            position: absolute;
            font-size: 56rpx;
            font-weight: bold;
            color: #fff;
            top: 80rpx;
            left: 28rpx;
        }

        .card-detail__recharge {
            width: 136rpx;
            height: 64rpx;
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28rpx;
            color: #08bfa8;
            position: absolute;
            top: 90rpx;
            right: 28rpx;
            border-radius: 34rpx;
        }

        .card-detail__no {
            position: absolute;
            left: 28rpx;
            bottom: 28rpx;
            font-size: 26rpx;
            color: #fff;
            opacity: 0.8;
        }
    }

    .list {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 30rpx;
        padding-bottom: 50rpx;

        .card-item {
            width: 694rpx;
            margin-bottom: 30rpx;
            box-sizing: border-box;
            padding: 28rpx;
            background-color: #ffffff;
            border-radius: 24rpx;
            display: flex;
            flex-direction: column;

            &.card-consume {
                .card-item__top {
                    .card-item__value {
                        color: #ff5e5e;
                    }
                }
            }

            &.card-recharge {
                .card-item__top {
                    .card-item__value {
                        color: #1078fe !important;
                    }
                }
            }

            .card-item__top {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 16rpx;

                .card-item__title {
                    display: flex;
                    align-items: center;
                    font-size: 32rpx;
                    font-weight: bold;

                    img {
                        width: 36rpx;
                        height: 36rpx;
                        margin-right: 16rpx;
                    }
                }

                .card-item__value {
                    font-size: 32rpx;
                    font-weight: bold;
                }
            }

            .card-item__refund{
                width: 100%;
                font-size: 24rpx;
                line-height: 32rpx;
                color: #9a9a9a;
                display: flex;
                justify-content: flex-end;
                margin-bottom: 16rpx;
            }

            .card-item__bottom {
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 24rpx;
                line-height: 32rpx;
                color: #9a9a9a;
            }
        }

        .empty {
            font-size: 24rpx;
            line-height: 1;
            color: #999;
            margin-top: 100rpx;
        }

        .load-more {
            width: 100%;
            font-size: 24rpx;
            line-height: 1;
            color: #08bfa8;
            padding: 20rpx 0;
            text-align: center;
        }

        .no-more {
            width: 100%;
            font-size: 24rpx;
            line-height: 1;
            color: #ccc;
            padding: 20rpx 0 40rpx;
            text-align: center;
        }
    }

    .bind-modal {
        width: 530rpx;
        height: 406rpx;
        background-color: #fff;
        border-radius: 24rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-sizing: border-box;
        padding: 60rpx 50rpx 42rpx;
        background-repeat: no-repeat;
        background-position: center top;
        background-size: contain;
        transition-duration: 0.2s;

        .modal-title {
            width: 100%;
            font-size: 34rpx;
            line-height: r8rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 28rpx;
        }

        .modal-input {
            background-color: #f4f8fb;
            border-radius: 24rpx;
            width: 430rpx;
            height: 98rpx;
            border: none;
            box-sizing: border-box;
            padding: 29rpx 30rpx;
            margin-bottom: 42rpx;

            input {
                font-size: 28rpx;
                line-height: 40rpx;
                height: 40rpx;
                font-weight: bold;
            }
        }

        .modal-footer {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .modal-btn {
                flex: none;
                width: 200rpx;
                height: 88rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 30rpx;
                color: #666666;
                background-color: #ededed;
                border-radius: 50rpx;
                font-weight: bold;

                &.confirm {
                    background: linear-gradient(222.93deg, rgba(139, 218, 176, 1) 0%, rgba(8, 191, 168, 1) 100%);
                    color: #fff;

                    &.disabled {
                        opacity: 0.4;
                    }
                }
            }
        }
    }
}
</style>
